package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbImageMapper;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TbAtta;
import com.bwie.pojo.TbImage;
import com.bwie.pojo.TbProd;
import com.bwie.service.TbProdService;
import com.bwie.mapper.TbProdMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.Result;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.ProdPageVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author lenovo
 * @description 针对表【tb_prod(商品表)】的数据库操作Service实现
 * @createDate 2025-05-26 16:49:26
 */
@Service
public class TbProdServiceImpl extends ServiceImpl<TbProdMapper, TbProd>
        implements TbProdService {

    @Autowired
    TbProdMapper tbProdMapper;
    @Autowired
    HttpServletRequest request;

    @Autowired
    TbImageMapper tbImageMapper;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    ElasticsearchRestTemplate elasticSearchRestTemplate;


    @Override
    public Result getProdList(PageInfoVo pageInfoVo) {

        Page<TbProd> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        QueryWrapper<TbProd> wrapper = new QueryWrapper<>();


        Page<TbProd> tbProdPage = tbProdMapper.getProdList(page, pageInfoVo);

        return Result.ok().setData(tbProdPage);
    }

    @Override
    public Result addProd(TbProd tbProd) {

        //对Spu校验
        TbProd prod = tbProdMapper.selectOne(
                new QueryWrapper<TbProd>().lambda().eq(TbProd::getProdSpu, tbProd.getProdSpu())
        );
        if (prod != null) {
            return Result.error().setMsg("Sup不能重复");
        }

        TbProd prod1 = tbProdMapper.selectOne(
                new QueryWrapper<TbProd>().lambda().eq(TbProd::getProdName, tbProd.getProdName())
        );
        if (prod1 != null) {
            return Result.error().setMsg("商品名称不能重复");
        }

        String token = request.getHeader("token");
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        String realName = body.get("realName", String.class);


        tbProd.setCreateTime(new Date());
        tbProd.setCreateBy(realName);
        tbProd.setProdStatus(0);


        tbProdMapper.insert(tbProd);


        //添加图片 （多图片上传）
//        if (tbProd.getTbImageList() != null && tbProd.getTbImageList().size() > 0) {
//            for (TbImage tbImage : tbProd.getTbImageList()) {
//                tbImage.setProdId(tbProd.getProdId());
//                tbImageMapper.insert(tbImage);
//            }
//        }
        return Result.ok();
    }

    @Override
    public Result deleteAll(List<TbProd> prodList) {

        for (TbProd prod : prodList) {
            tbProdMapper.deleteById(prod);
        }
        return Result.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addProdAtta(TbAtta tbAtta) {

        //确实商品是否存在
        TbProd tbProd = tbProdMapper.selectById(tbAtta.getProdId());

        if (tbProd == null) {
            return Result.error().setMsg("商品不存在");
        }

        //更新商品信息
        tbProd.setProdVideo(tbAtta.getProdVideo());
        tbProd.setUpType(tbAtta.getUpType());
        tbProd.setUpTime(tbAtta.getUpTime());

        tbProd.setDownType(tbAtta.getDownType());
        tbProd.setDownTime(tbAtta.getDownTime());
        tbProdMapper.updateById(tbProd);


        tbImageMapper.delete(new QueryWrapper<TbImage>().lambda().eq(TbImage::getProdId, tbProd.getProdId()));


        //添加商品轮播图
        if (tbAtta.getImageList() != null && tbAtta.getImageList().size() > 0) {
            for (TbImage tbImage : tbAtta.getImageList()) {
                tbImage.setProdId(tbProd.getProdId());
                tbImageMapper.insert(tbImage);
            }
        }
        return Result.ok();
    }

    @Override
    public Result checkProd(TbProd tbProd) {

        //确定商品是否存在
        TbProd prod = tbProdMapper.selectById(tbProd.getProdId());
        if (prod == null) {
            return Result.error().setMsg("商品不存在");
        }

        // 审核商品   如果审核驳回必须填写原因
        if (tbProd.getCheckStatus() == 2) {
            if (tbProd.getCheckReason() == null) {
                return Result.error().setMsg("请输入审核驳回的原因");
            }
        }

        String token = request.getHeader("token");
        if (token == null) {
            return Result.error().setMsg("请先登录");
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);


        prod.setCheckId(userId);
        prod.setCheckStatus(tbProd.getCheckStatus());
        prod.setCheckReason(tbProd.getCheckReason());

        if (tbProd.getCheckStatus() == 1) {
            prod.setProdStatus(1);
        }
        tbProdMapper.updateById(prod);


        String message = JSON.toJSONString(prod);

        //如果审核通过，发送短信通知用户
        kafkaTemplate.send("topic-prod", message);


        //如果什么驳回发送邮件

        return Result.ok();
    }

    @Override
    public Result getProdListEs(ProdPageVo prodPageVo) {

        //构造分页参数
        Integer pageNum = 0;
        if (prodPageVo.getPageNum() > 0) {
            pageNum = prodPageVo.getPageNum() - 1;
        }

        PageRequest pageRequest = PageRequest.of(pageNum, prodPageVo.getPageSize());

        //构造查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        if (StringUtils.isNotEmpty(prodPageVo.getKeyWord())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("prodName", prodPageVo.getKeyWord()));
        }

        HighlightBuilder prodName = new HighlightBuilder().field("prodName").preTags("<font color='red'>").postTags("</font>");


        //开始查询
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withPageable(pageRequest)
                .withQuery(boolQueryBuilder)
                .withHighlightBuilder(prodName);

        SearchHits<TbProd> searchHits = elasticSearchRestTemplate.search(nativeSearchQueryBuilder.build(), TbProd.class);


        //解析结果
        long total = searchHits.getTotalHits();

        ArrayList<TbProd> records = new ArrayList<>();

        for (SearchHit<TbProd> searchHit : searchHits.getSearchHits()) {

            TbProd tbProd = searchHit.getContent();

            List<String> prodNameList = searchHit.getHighlightField("prodName");

            if (prodNameList != null && prodNameList.size() > 0) {
                String pName = prodNameList.get(0);
                tbProd.setProdName(pName);
            }


            records.add(tbProd);

        }


        // 返回结果
        HashMap<String, Object> map = new HashMap<>(2);

        map.put("total", total);
        map.put("records", records);

        return Result.ok().setData(map);
    }


    /**
     * @param :
     * @return void
     * @author :杨珂
     * @description 接收kafka消息
     * @date 2025/6/4 16:58
     */
    @KafkaListener(topics = "topic-prod")
    public void recvProdMessage(String message, Acknowledgment acknowledgment) {

        System.out.println("接收到消息" + message);
        //还原消息
        TbProd tbProd = JSON.parseObject(message, TbProd.class);
        if (tbProd.getCheckStatus() == 2) {
            try {
                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
                messageHelper.setTo("2608037599@qq.com");
                messageHelper.setFrom("2608037599@qq.com");
                messageHelper.setSubject("商品审核结果通知");

                String body = "商品审核被驳回" + tbProd.getCheckReason();
                messageHelper.setText(body);

                javaMailSender.send(mimeMessage);
                System.out.println("发送邮件成功");
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        //发送短信
        if (tbProd.getCheckStatus() == 1) {
            String msg = "商品审核通过" + tbProd.getProdName();
            MobileMessageUtil.sendMobileMessage("19292280811", msg);
            System.out.println("发送短信成功");


            //同步到ES 中
            IndexOperations indexOps = elasticSearchRestTemplate.indexOps(TbProd.class);

            if (!indexOps.exists()) {

                indexOps.create();

                Document mapping = indexOps.createMapping();
                indexOps.putMapping(mapping);
            }
            //同步商品到ES
            TbProd prod = tbProdMapper.getprodById(tbProd.getProdId());

            elasticSearchRestTemplate.save(prod);

        }

        //消息确认
        acknowledgment.acknowledge();
        System.out.println("确认消息：商品审核消息");


    }


}




